<template>
  <div class="shop-customer-service">
    <div class="header">
      <h2>客服聊天管理</h2>
      <div class="stats">
        <el-button @click="goToHomepage" type="primary" size="small">返回主页</el-button>
        <el-tag type="info">会话总数: {{ sessions.length }}</el-tag>
        <el-tag type="warning">未读消息: {{ totalUnreadCount }}</el-tag>
      </div>
    </div>
    
    <!-- 会话列表 -->
    <div class="session-list">
      <div 
        v-for="session in sessions" 
        :key="session.sessionId"
        :class="['session-item', activeSessionId === session.sessionId ? 'active' : '']"
        @click="selectSession(session)"
      >
        <div class="session-avatar">
          <el-avatar :size="40" :src="getBuyerAvatar(session.buyerId)" />
        </div>
        <div class="session-info">
          <div class="buyer-name">{{ session.buyerName }}</div>
          <div class="last-message">{{ session.lastMessage || '暂无消息' }}</div>
          <div class="session-time">{{ formatTime(session.lastMessageTime) }}</div>
        </div>
        <div class="session-status">
          <el-badge :value="session.unreadCount" :max="99" v-if="session.unreadCount > 0">
            <el-icon><ChatDotRound /></el-icon>
          </el-badge>
        </div>
      </div>
      
      <div v-if="sessions.length === 0" class="empty-state">
        <el-empty description="暂无聊天会话" />
      </div>
    </div>
    
    <!-- 聊天窗口 -->
    <div class="chat-window" v-if="activeSession">
      <div class="chat-header">
        <div class="chat-title">
          <el-avatar :size="32" :src="getBuyerAvatar(activeSession.buyerId)" />
          <span>{{ activeSession.buyerName }}</span>
        </div>
        <div class="chat-actions">
          <el-button size="small" @click="closeSession(activeSession.sessionId)">
            结束会话
          </el-button>
        </div>
      </div>
      
      <!-- 消息列表 -->
      <div class="messages-container" ref="messagesContainer">
        <div 
          v-for="message in activeMessages" 
          :key="message.messageId"
          :class="['message-item', message.senderId === currentShop.id ? 'own-message' : 'other-message']"
        >
          <div class="message-avatar">
            <el-avatar :size="28" :src="getAvatar(message.senderId)" />
          </div>
          <div class="message-content">
            <div class="message-sender">{{ message.senderName }}</div>
            <div class="message-bubble">{{ message.content }}</div>
            <div class="message-time">{{ formatTime(message.sendTime) }}</div>
          </div>
        </div>
      </div>
      
      <!-- 输入区域 -->
      <div class="input-container">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="3"
          placeholder="请输入回复内容..."
          maxlength="500"
          show-word-limit
          @keydown.enter="handleSendMessage"
        />
        <div class="input-actions">
          <el-button 
            type="primary" 
            @click="handleSendMessage" 
            :loading="sending"
            :disabled="!inputMessage.trim()"
          >
            发送
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { memoryChatApi } from '../apis/memoryChat.js'
import { useUserStore } from '../stores/user.js'

// Store
const userStore = useUserStore()

// Reactive data
const sessions = ref([])
const activeSessionId = ref('')
const activeMessages = ref([])
const inputMessage = ref('')
const sending = ref(false)
const messagesContainer = ref(null)

const currentShop = reactive({
  id: userStore.myShop?.shopId || '',
  name: userStore.myShop?.shopName || '店铺'
})

// Computed
const totalUnreadCount = computed(() => {
  return sessions.value.reduce((total, session) => total + (session.unreadCount || 0), 0)
})

const activeSession = computed(() => {
  return sessions.value.find(session => session.sessionId === activeSessionId.value)
})

// Methods
const loadSessions = async () => {
  try {
    const response = await memoryChatApi.getShopSessions(currentShop.id)
    if (response.code === 200) {
      sessions.value = response.data || []
      
      // 如果没有活跃会话，选择第一个有未读消息的会话
      if (!activeSessionId.value && sessions.value.length > 0) {
        const unreadSession = sessions.value.find(session => session.unreadCount > 0)
        if (unreadSession) {
          selectSession(unreadSession)
        } else {
          selectSession(sessions.value[0])
        }
      }
    }
  } catch (error)
  {
    console.error('加载会话列表失败:', error)
    ElMessage.error('加载会话列表失败')
  }
}

const selectSession = async (session) => {
  activeSessionId.value = session.sessionId
  await loadMessages(session.sessionId)
  
  // 标记已读
  if (session.unreadCount > 0) {
    markAllMessagesAsRead(session.sessionId)
  }
}

const loadMessages = async (sessionId) => {
  try {
    const response = await memoryChatApi.getSessionMessages(sessionId)
    if (response.code === 200) {
      activeMessages.value = response.data || []
      scrollToBottom()
    }
  } catch (error) {
    console.error('加载消息失败:', error)
    ElMessage.error('加载消息失败')
  }
}

const handleSendMessage = async () => {
  if (!inputMessage.value.trim() || !activeSession.value) return
  
  sending.value = true
  try {
    const messageData = {
      sessionId: activeSession.value.sessionId,
      senderId: currentShop.id,
      senderName: currentShop.name,
      receiverId: activeSession.value.buyerId,
      receiverName: activeSession.value.buyerName,
      content: inputMessage.value.trim(),
      messageType: 'text'
    }
    
    const response = await memoryChatApi.sendMessage(messageData)
    if (response.code === 200) {
      inputMessage.value = ''
      await loadMessages(activeSession.value.sessionId)
      await loadSessions() // 刷新会话列表
    } else {
      ElMessage.error(response.message || '发送失败')
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送失败，请稍后重试')
  } finally {
    sending.value = false
  }
}

const closeSession = async (sessionId) => {
  try {
    const response = await memoryChatApi.closeSession(sessionId)
    if (response.code === 200) {
      ElMessage.success('会话已结束')
      await loadSessions()
      activeSessionId.value = ''
      activeMessages.value = []
    } else {
      ElMessage.error(response.message || '结束会话失败')
    }
  } catch (error) {
    console.error('结束会话失败:', error)
    ElMessage.error('结束会话失败')
  }
}

const markAllMessagesAsRead = async (sessionId) => {
  try {
    // 这里可以优化为批量标记已读
    const session = sessions.value.find(s => s.sessionId === sessionId)
    if (session) {
      // 在实际实现中，这里应该调用批量标记已读的API
      // 暂时简单处理，重新加载会话列表
      await loadSessions()
    }
  } catch (error) {
    console.error('标记已读失败:', error)
  }
}

const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

const getAvatar = (userId) => {
  return userId === currentShop.id ? '/shop-avatar.png' : '/user-avatar.png'
}

const getBuyerAvatar = (buyerId) => {
  return '/user-avatar.png'
}

const formatTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  return `${date.getMonth() + 1}/${date.getDate()} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

const goToHomepage = () => {
  window.location.href = 'http://localhost:5173/homepage'
}

// 轮询获取新消息
let pollingInterval = null
const startPolling = () => {
  pollingInterval = setInterval(async () => {
    await loadSessions()
    if (activeSession.value) {
      await loadMessages(activeSession.value.sessionId)
    }
  }, 5000) // 每5秒轮询一次
}

const stopPolling = () => {
  if (pollingInterval) {
    clearInterval(pollingInterval)
    pollingInterval = null
  }
}

// Lifecycle
onMounted(() => {
  if (currentShop.id) {
    loadSessions()
    startPolling()
  }
})

// Watch shop info
watch(() => userStore.myShop, (newShop) => {
  if (newShop) {
    currentShop.id = newShop.shopId
    currentShop.name = newShop.shopName
    loadSessions()
  }
}, { immediate: true })

// Cleanup
import { onUnmounted } from 'vue'
onUnmounted(() => {
  stopPolling()
})
</script>

<style scoped>
.shop-customer-service {
  display: flex;
  height: 600px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
}

.header {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stats {
  display: flex;
  gap: 8px;
}

.session-list {
  width: 300px;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.session-item {
  display: flex;
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.session-item:hover {
  background-color: #f5f7fa;
}

.session-item.active {
  background-color: #ecf5ff;
}

.session-info {
  flex: 1;
  margin-left: 12px;
  min-width: 0;
}

.buyer-name {
  font-weight: bold;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.last-message {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 4px;
}

.session-time {
  font-size: 12px;
  color: #c0c4cc;
}

.session-status {
  display: flex;
  align-items: center;
}

.empty-state {
  padding: 40px 20px;
  text-align: center;
}

.chat-window {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 12px 16px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: bold;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.message-item {
  display: flex;
  margin-bottom: 16px;
  align-items: flex-start;
}

.own-message {
  flex-direction: row-reverse;
  
  .message-content {
    align-items: flex-end;
    margin-right: 12px;
  }
  
  .message-bubble {
    background-color: #409eff;
    color: white;
  }
}

.other-message {
  .message-content {
    align-items: flex-start;
    margin-left: 12px;
  }
  
  .message-bubble {
    background-color: #f5f7fa;
    color: #606266;
  }
}

.message-content {
  display: flex;
  flex-direction: column;
  max-width: 70%;
}

.message-sender {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.message-bubble {
  padding: 8px 12px;
  border-radius: 8px;
  word-wrap: break-word;
}

.message-time {
  font-size: 12px;
  color: #c0c4cc;
  margin-top: 4px;
}

.input-container {
  padding: 16px;
  border-top: 1px solid #e4e7ed;
  
  .input-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 12px;
  }
}
</style>